<script setup>
import { ref, nextTick, onMounted, onUnmounted } from "vue";
import * as echarts from "echarts";

let chartBar;
const chartBarDom = ref(null);

onMounted(() => {
  nextTick(() => {
    createBarChart();
    window.addEventListener("resize", () => {
      chartBar.resize();
    });
  });
});

onUnmounted(() => {
  window.removeEventListener("resize", () => {
    chartBar.resize();
  });
});

const createBarChart = () => {
  if (!chartBarDom.value) return;

  //  ----------销毁与创建----------开始
  if (chartBar) {
    chartBar = echarts.dispose(chartBarDom.value);
  }
  if (!chartBar) {
    chartBar = echarts.init(chartBarDom.value);
  }

  //  ----------销毁与创建----------结束

  chartBar.setOption(chartOption());

  // 自动调整图表大小
  chartBar.resize({
    animation: {
      duration: 2800,
      easing: "cubicInOut",
      // delay: 500,
    },
  });
};

const chartOption = () => {
  return {
    // ECharts 配置项
    xAxis: {
      type: "category",
      data: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
    },
    yAxis: {
      type: "value",
    },
    series: [
      {
        data: [120, 200, 150, 80, 70, 110, 130],
        type: "bar",
      },
    ],
  };
};
</script>

<template>
  <div
    ref="chartBarDom"
    :style="{ width: '100%', height: '100%' }"
  ></div>
</template>
